package com.lightkits.wms.domain.purchasereceive.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.db.entity.BdTransaction;
import com.lightkits.common.db.entity.FndEventTypeBase;
import com.lightkits.common.db.entity.FndResourceTl;
import com.lightkits.common.db.entity.FndTransactionTypeBase;
import com.lightkits.common.db.entity.FndWarehouse;
import com.lightkits.common.db.entity.FndWmArea;
import com.lightkits.common.db.entity.FndWorker;
import com.lightkits.common.db.entity.ScmPoHeader;
import com.lightkits.common.db.entity.ScmPoLine;
import com.lightkits.common.db.entity.ScmPoTrack;
import com.lightkits.common.db.entity.event.BdEvent;
import com.lightkits.common.db.entity.event.BdEventRecord;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.model.CheckResult;
import com.lightkits.framework.common.utility.date.DateUtil;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.object.ParseUtil;
import com.lightkits.framework.soa.client.id.GetGlobalIDRequestType;
import com.lightkits.framework.soa.client.id.GetGlobalIDResponseType;
import com.lightkits.framework.soa.client.id.IDServiceClient;
import com.lightkits.wms.client.DocumentServiceClient;
import com.lightkits.wms.domain.purchasereceive.service.CreateParamsDomain;
import com.lightkits.wms.domain.stocktransfer.service.impl.SubStockTransferDomainImpl;
import com.lightkits.wms.dto.document.GenerateDocNumRequestType;
import com.lightkits.wms.dto.document.GenerateDocNumResponseType;
import com.lightkits.wms.dto.purchasereceive.models.SavePoParamsDTO;
import com.lightkits.wms.dto.tagservice.model.TagViewDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * CreateEventDomainImpl
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/26 15:32
 */
@Service
public class CreateParamsDomainImpl implements CreateParamsDomain {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubStockTransferDomainImpl.class);

    private final IDServiceClient idAdapterService;


    private final DocumentServiceClient client;

    @Autowired
    public CreateParamsDomainImpl(IDServiceClient idAdapterService, DocumentServiceClient client) {
        this.idAdapterService = idAdapterService;
        this.client = client;
    }

    @Override
    public BdEvent createEvent(SavePoParamsDTO dto, Long eventTypeId) {
        BdEvent event = new BdEvent();
        try {
            FndEventTypeBase eventTypeBase = new FndEventTypeBase()
                    .selectById(eventTypeId);
            event.setEventRequestId(dto.getEventRequestId());
            event.setEventTypeId(eventTypeId);
            event.setEventTypeCode(eventTypeBase.getEventTypeCode());
            event.setOrganizationId(ParseUtil.tryLongWithException(dto.getOrgId()));
            event.setItemId(ParseUtil.tryLongWithException(dto.getItemId()));
            if (!ObjectUtil.isNullOrEmpty(dto.getReceiveWarehouseId())) {
                event.setWarehouseId(ParseUtil.tryLongWithException(dto.getReceiveWarehouseId()));
            }
            if (!ObjectUtil.isNullOrEmpty(dto.getReceiveWmAreaId())) {
                event.setWmAreaId(ParseUtil.tryLongWithException(dto.getReceiveWmAreaId()));
            }
            event.setWorkerId(ParseUtil.tryLongWithException(dto.getReceiveWorker()));

        } catch (Exception e) {
            LOGGER.error("Create Event error", e);
            throw new LightKitsBizException(e);
        }
        return event;
    }

    @Override
    public BdEventRecord createRecord(String objectType, Long objectId, String keyValue, String recordType) {
        BdEventRecord record = new BdEventRecord();
        try {
            record.setObjectId(objectId);
            record.setKeyValue(keyValue);
            record.setObjectType(objectType);
            record.setRecordType(recordType);
        } catch (Exception e) {
            LOGGER.error("Create Event Records  error", e);
            throw new LightKitsBizException(e);
        }
        return record;
    }

    @Override
    public BdTransaction createTranscation(SavePoParamsDTO dto, Long transTypeId, Long moveTypeId) {
        BdTransaction trans = new BdTransaction();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        try {
            GetGlobalIDRequestType idRequest = new GetGlobalIDRequestType();
            idRequest.setCount(1);
            GetGlobalIDResponseType idResponse = idAdapterService.getGlobalId(idRequest);
            Iterator<Long> sfIds = idResponse.getIds().iterator();
            FndTransactionTypeBase base = new FndTransactionTypeBase()
                    .selectById(transTypeId);
            trans.setTransactionTypeId(transTypeId);
            trans.setTransactionTypeCode(base.getTransactionTypeCode());
            trans.setOrganizationId(ParseUtil.tryLongWithException(dto.getOrgId()));
            trans.setId(sfIds.next());
            trans.setItemId(ParseUtil.tryLongWithException(dto.getItemId()));
            trans.setTransactionUom(dto.getUomCode());
            trans.setTransactionDate(format.parse(format.format(new Date())));
            ScmPoHeader header = new ScmPoHeader().selectById(dto.getPoId());
            ScmPoLine line = new ScmPoLine().selectById(dto.getPoLineId());
            trans.setDocumentLineId(line.getId());
            trans.setDocumentId(header.getId());
            trans.setDocumentTypeCode("PO");
            trans.setDocumentNum(header.getPoNum());
            format.applyPattern("HH:mm:ss");
            trans.setTransactionTime(format.parse(format.format(new Date())));
            trans.setTransactionQty(new BigDecimal(dto.getReceiveQty()));
            trans.setWarehouseId(ParseUtil.tryLongWithException(dto.getReceiveWarehouseId()));
            if (!ObjectUtil.isNullOrEmpty(dto.getReceiveWmAreaId())) {
                trans.setWmAreaId(ParseUtil.tryLongWithException(dto.getReceiveWmAreaId()));
            }
            trans.setWorkerId(ParseUtil.tryLongWithException(dto.getReceiveWorker()));
            trans.setEventRequestId(dto.getEventRequestId());
            FndWorker worker = new FndWorker().selectById(dto.getReceiveWorker());
            trans.setWorkerNumber(worker.getWorkerNumber());
            trans.setTransactionReasonCode(moveTypeId);
            trans.setRemark(line.getRemark());
        } catch (Exception e) {
            LOGGER.error("create Transcation.error", e);
            throw new LightKitsBizException(e);
        }
        return trans;

    }

    @Override
    public ScmPoTrack createPoTrack(SavePoParamsDTO dto, String actionReord) {
        ScmPoTrack poTrack = new ScmPoTrack();
        try {
            poTrack.setItemId(ParseUtil.tryLongWithException(dto.getItemId()));
            poTrack.setPoHeaderId(ParseUtil.tryLongWithException(dto.getPoId()));
            poTrack.setPoLineId(ParseUtil.tryLongWithException(dto.getPoLineId()));
            poTrack.setKeyValue(dto.getReceiveQty());
            poTrack.setTrackType("PO_RECEIVE");
            poTrack.setActionRecord(actionReord);
            poTrack.setWorkerId(ParseUtil.tryLongWithException(dto.getReceiveWorker()));
            FndResourceTl worker = new FndResourceTl().selectOne(
                    new EntityWrapper().eq(FndResourceTl.RESOURCE_ID, dto.getReceiveWorker()));
            poTrack.setWorkerName(worker.getResourceName());
            poTrack.setOrganizationId(ParseUtil.tryLongWithException(dto.getOrgId()));
            poTrack.setTrackTime(new Date());
            poTrack.setWarehouseId(ParseUtil.tryLongWithException(dto.getReceiveWarehouseId()));
            FndWarehouse warehouse = new FndWarehouse().selectById(dto.getReceiveWarehouseId());
            poTrack.setWarehouseCode(warehouse.getWarehouseCode());

            if (!ObjectUtil.isNullOrEmpty(dto.getReceiveWmAreaId())) {
                poTrack.setWmAreaId(ParseUtil.tryLongWithException(dto.getReceiveWmAreaId()));
                FndWmArea wmArea = new FndWmArea().selectById(dto.getReceiveWmAreaId());
                if (wmArea != null) {
                    poTrack.setWmAreaCode(wmArea.getWmAreaCode());
                }
            }

        } catch (Exception e) {
            LOGGER.error("create Po Track .error", e);
            throw new LightKitsBizException(e);
        }
        return poTrack;
    }

    @Override
    public List<TagViewDto> createTagParams(SavePoParamsDTO dto,
                                            String type,
                                            BdEvent event) {
        List<TagViewDto> viewDtos = new ArrayList<>();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        int size = 0;
        if (type.equals("1U1S")) {
            size = Integer.valueOf(dto.getReceiveQty());
        } else {
            size = 1;
        }
        GenerateDocNumRequestType request = new GenerateDocNumRequestType();
        request.setCount(size);
        request.setSize(3);
        request.setType("1");
        request.setField1(df.format(new Date()));
        GenerateDocNumResponseType response = client.generateDocNumber(request);
        for (int i = 0; i < size; i++) {

            TagViewDto tagViewDto = new TagViewDto();
            tagViewDto.setEventId(event.getId());
            tagViewDto.setEventBy(event.getWorkerId());
            tagViewDto.setEventTime(DateUtil.toDateString(event.getCreationDate()));
            tagViewDto.setTagType(type);
            tagViewDto.setTagCode(response.getDocNumList().get(i));
            tagViewDto.setWarehouseId(dto.getReceiveWarehouseId());
            tagViewDto.setWmAreaId(dto.getReceiveWmAreaId());
            tagViewDto.setContainerOwnerType("OWN");
            tagViewDto.setTagThingType("ITEM");
            tagViewDto.setItemId(dto.getItemId());
            tagViewDto.setContainerId("1234567");
            tagViewDto.setUomCode(dto.getUomCode());
            if (type.equals("1U1S")) {
                tagViewDto.setQuantity("1");
            } else {
                tagViewDto.setQuantity(dto.getReceiveQty());
            }
            tagViewDto.setDocumentId(dto.getPoLineId());
            tagViewDto.setLotNumber(dto.getLotCode());
            tagViewDto.setOwnerType("OWN");
            tagViewDto.setOwnerOrgId(dto.getOrgId());
            tagViewDto.setQcStatus("OK");
            viewDtos.add(tagViewDto);
        }
        return viewDtos;
    }
}
